package models

import (
	"database/sql"
	"time"
)

type BookExcerpt struct {
	ID        int64  `json:"id"`
	BookID    int64  `json:"book_id"`
	Excerpt   string `json:"excerpt"`
	Thought   string `json:"thought"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

// CreateBookExcerpt 创建新的书摘
func CreateBookExcerpt(db *sql.DB, excerpt *BookExcerpt) error {
	now := time.Now().Format("2006-01-02 15:04:05")
	excerpt.CreatedAt = now
	excerpt.UpdatedAt = now

	result, err := db.Exec(
		"INSERT INTO book_excerpt (book_id, excerpt, thought, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",
		excerpt.BookID,
		excerpt.Excerpt,
		excerpt.Thought,
		excerpt.CreatedAt,
		excerpt.UpdatedAt,
	)
	if err != nil {
		return err
	}

	id, err := result.LastInsertId()
	if err != nil {
		return err
	}
	excerpt.ID = id
	return nil
}

// UpdateBookExcerpt 更新书摘
func UpdateBookExcerpt(db *sql.DB, excerpt *BookExcerpt) error {
	excerpt.UpdatedAt = time.Now().Format("2006-01-02 15:04:05")

	_, err := db.Exec(
		"UPDATE book_excerpt SET excerpt = ?, thought = ?, updated_at = ? WHERE id = ?",
		excerpt.Excerpt,
		excerpt.Thought,
		excerpt.UpdatedAt,
		excerpt.ID,
	)
	return err
}

// GetBookExcerptsByBookID 获取指定书籍的所有书摘
func GetBookExcerptsByBookID(db *sql.DB, bookID int64) ([]BookExcerpt, error) {
	rows, err := db.Query(
		"SELECT id, book_id, excerpt, thought, created_at, updated_at FROM book_excerpt WHERE book_id = ? ORDER BY created_at DESC",
		bookID,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var excerpts []BookExcerpt
	for rows.Next() {
		var excerpt BookExcerpt
		err := rows.Scan(
			&excerpt.ID,
			&excerpt.BookID,
			&excerpt.Excerpt,
			&excerpt.Thought,
			&excerpt.CreatedAt,
			&excerpt.UpdatedAt,
		)
		if err != nil {
			return nil, err
		}
		excerpts = append(excerpts, excerpt)
	}
	return excerpts, nil
}
